package com.zhiyizhen.handheld.component.pharmacy;

import android.os.Bundle;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.RecyclerViewUtil;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.constant.AppConstant;
import com.zhiyizhen.handheld.common.event.AddRegimenRecordEvent;
import com.zhiyizhen.handheld.common.view.BaseFragment;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.pharmacy.adapter.RegimenHistoryAdapter;
import com.zhiyizhen.handheld.component.pharmacy.api.IRegimenDosageService;
import com.zhiyizhen.handheld.component.pharmacy.bean.RegimenRecordBean;
import com.zhiyizhen.handheld.databinding.FragmentRegimenHistoryBinding;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

/**
 * 配药历史
 */
public class RegimenHistoryFragment extends BaseFragment {
    private FragmentRegimenHistoryBinding binding;
    private RegimenHistoryAdapter adapter;
    private int mPage = 1;
    private LoginBean loginBean;
    private String patientId;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentRegimenHistoryBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loginBean = DataCache.getLoginBean();
        initView();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void setData(String patientId) {
        this.patientId = patientId;
        loadData(mPage);
        binding.emptyView.setVisibility(View.GONE);
        binding.recyclerView.setVisibility(View.VISIBLE);
    }

    public void setEmptyData() {
        binding.emptyView.setVisibility(View.VISIBLE);
        binding.recyclerView.setVisibility(View.GONE);
    }

    public void reloadData() {
        loadData(mPage);
    }

    private void initView() {
        RecyclerViewUtil.configLVRecyclerView(getContext(), binding.recyclerView);
        adapter = new RegimenHistoryAdapter(this.getContext());
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(1);
            }

            @Override
            public void onLoadMore() {
                loadData(mPage + 1);
            }
        });
    }

    private void loadData(final int page) {
        Map<String, Object> map = new ArrayMap<>();
        map.put(AppConstant.PAGE_NO, page);
        map.put(AppConstant.PAGE_SIZE, AppConstant.PER_PAGE);

        ServiceFactory.getService(IRegimenDosageService.class)
                .getDispenseHistoryList(loginBean.getToken(), loginBean.getClinicId(), patientId, page, AppConstant.PER_PAGE)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    boolean hasMore = true;
                    boolean success = false;

                    @Override
                    protected void onSuccess(ResponseData<List<RegimenRecordBean>> responseData) {
                        success = true;
                        mPage = page;

                        List<RegimenRecordBean> list = responseData.getData();
                        if (mPage == 1) {
                            adapter.setData(list);
                        } else {
                            adapter.addAll(list);
                        }
                        hasMore = (list != null && list.size() == AppConstant.PER_PAGE);
                    }

                    @Override
                    protected void onFinally() {
                        RecyclerViewUtil.loadComplete(binding.recyclerView, mPage, success, !hasMore, adapter.getItemCount() <= 0);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addNewRecord(AddRegimenRecordEvent event) {
        reloadData();
    }
}
